<template>
  <div class="app-container">
    <div>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="showForm = true"
      >添加广告</el-button>
    </div>

    <el-table
      :data="list"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      lazy
      default-expand-all
      :tree-props="{children: 'child', hasChildren: 'hasChildren'}">
      <el-table-column
        prop="id"
        width="100"
        label="序号">
      </el-table-column>
      <el-table-column
        prop="title"
        label="标题">
      </el-table-column>
      <el-table-column
        prop="cid"
        label="类型">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.cid==1?'':scope.row.cid==2?'danger':'warning'">{{scope.row.cid==1?"类目":scope.row.cid==2?"特惠":"快讯"}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="image"
        width="160"
        label="图片">
        <template slot-scope="scope">
          <a target="_blank" :href="scope.row.image[0].url">
            <img :src="scope.row.image[0].url" alt="广告图">
          </a>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="160">
        <template slot-scope="scope">
          <el-button v-show='scope.row.status == 1' @click="disableEvent(scope.row, 2)" type="primary" size="small">禁用</el-button>
          <el-button v-show='scope.row.status == 2' @click="disableEvent(scope.row, 1)" type="success" size="small">启用</el-button>
          <!-- <el-button @click="editEvent(scope.row)" type="primary" size="small">修改</el-button> -->
          <el-button @click="delEvent(scope.row)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog title="添加广告" :visible.sync="showForm">
      <advert-form
        @change='onChange'
        :imageUrl='imageUrl'
        :item='item'
        @submit='onSubmit'
        @choiseAc='choiseAc'
      />
    </el-dialog>

    <el-dialog title="裁切" :visible.sync="cropper" @closed='closed'>
      <cropper-image
        :image='image'
        ref='cropper'
      />

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="uploadImage">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="选择活动" :visible.sync="activity">
      <choise ref='choise' :list='choiseItems' />

      <span slot="footer" class="dialog-footer">
        <el-button @click="activity = false">取 消</el-button>
        <el-button type="primary" @click="onChoise">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CropperImage from '@/components/Cropper/index.vue'
import AdvertForm from './advertForm.vue'
import Pagination from '@/components/Pagination'
import Choise from './choise.vue'
import axios from 'axios'
import { query, save, put, list, deleted } from '@/api/advert'
export default {
  components: {
    AdvertForm,
    CropperImage,
    Choise,
    Pagination
  },
  data() {
    return {
      list: [],
      id: 0, // 修改哪个
      loading: false,
      activity: false,
      showForm: false, // 显示添加广告组件
      cropper: false, // 显示裁切
      image: '', // 待裁切图片
      choiseItems: [],
      item: {
        cid: '',
        id: '',
        title: ''
      },
      imageUrl: {
        name: '',
        path: ''
      },
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
        sort: '-create_time',
        where: []
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 选择图片
    onChange(blob) {
      this.image = URL.createObjectURL(blob)
      this.cropper = true
    },
    getList() {
      list().then(res => {
        if (res.status) {
          this.list = res.data.data
        }
      })
    },
    // 禁用、启用
    disableEvent(row, flag) {
      const ti = Number(flag) === 1 ? '启用' : '禁用'
      this.$confirm(`确定${ti}【${row.title}】吗？`, row.title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.$store.commit('SHOW_LOADING')
        put(row.id, {
          status: flag
        }).then(res => {
          this.$message({
            type: 'success',
            message: '操作成功'
          })
          const li = this.list.find(c => c.id === row.id)
          this.$set(li, 'status', Number(flag))
          this.$store.commit('HIDE_LOADING')
        })
      })
    },
    delEvent(row) {
      this.$confirm(`确定删除【${row.title}】吗？`, row.title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        deleted(row.id).then(res => {
          this.$message({
            type: 'success',
            message: '操作成功'
          })
          this.list.splice(this.list.findIndex(c => c.id === row.id), 1)
          this.$store.commit('HIDE_LOADING')
        })
      })
    },
    editEvent(row) {
      this.showForm = true
    },
    closed() {
      this.$refs.cropper.cropper.destroy()
    },
    async uploadImage() {
      try {
        this.loading = true
        const blob = await this.$refs.cropper.getBlob()
        const formData = new FormData()
        formData.append('image', blob)
        const res = await axios({
          // url: '/aliyun/upload_image',
          url: '/admin/posts',
          // url: 'http://jiexun.3qiy.com/v1/aliyun/upload_image',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          method: 'POST'
        })
        this.imageUrl = {
          name: res.data.data._id,
          path: res.data.data._path
        }
        this.cropper = false
        this.loading = false
      } catch (error) {
        this.loading = false
        this.$message.error('图片上传失败')
      }
    },
    onChoise() {
      const result = this.$refs.choise.result()
      if (result === '') {
        this.$message.error('请选择活动')
        return
      }
      this.activity = false
      this.item = result
    },
    choiseAc(keywords) {
      this.activity = true
      this.$store.commit('SHOW_LOADING')
      query({ q: keywords })
        .then(res => {
          this.choiseItems = res.data
          this.$store.commit('HIDE_LOADING')
        })
    },
    onSubmit(form) {
      if (!this.imageUrl.name) {
        this.$message.error('请选择图片')
        return
      }
      save({
        cid: this.item.cid,
        rid: this.item.id,
        title: form.title,
        image: this.imageUrl.name,
        id: this.id
      }).then(res => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        this.getList()
        this.showForm = false
      })
    }
  }
}
</script>

<style lang="scss">
img {max-width: 100%;}
</style>
